<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>观察者模式</title>
</head>
<body>
<script>
    //有个人说者其实是监听者模式，简而言之就是一个一对一的模式
    //声明主体
    var PubSub=(function(){

        //创建一个对象
        var event={};
        return {
            on:function(eventName,callback){
                //将事件保存一起，保存为对象，称为订阅
                event[eventName]=callback;
            },
            off:function(eventName){
                //退订
                event[eventName]&&(delete event[eventName]);
            },
            emit:function(eventName){
                //发布
                event[eventName]&&event[eventName](arguments[1])
            }
        }
    })();
    //订阅相关信息
    PubSub.on("newspaper",function(){
        arguments[0] ?console.log(arguments[0] +"新一期报纸出来了"):console.log("无名氏报纸出来了");
    });
    PubSub.on("newspaper",function(){
        arguments[0] ?console.log(arguments[0] +"新1期报纸出来了"):console.log("无名氏111报纸出来了");
    });
    PubSub.on("news",function(){
        arguments[0] ?console.log(arguments[0] +"新闻出来了"):console.log("无名氏新闻出来了");
    });

    PubSub.emit("newspaper","bob");
    PubSub.emit("news","bob");
    PubSub.emit("newspaper");
    PubSub.emit("newspaper","john");
    PubSub.off("newspaper");
    //所以退订是全部人都退订了吗？缺点就是一个时间只能绑定一个人，删除了就把所以的删除了
    //PubSub.emit("newspaper","bob");
    PubSub.emit("news","bob");
    //PubSub.emit("newspaper");
    PubSub.emit("newspaper","john");
</script>
</body>
</html>